package com.example.bikemanagerjava.controller;

import com.example.bikemanagerjava.common.JwtTokenProvider;
import com.example.bikemanagerjava.common.Result;
import com.example.bikemanagerjava.entity.User;
import com.example.bikemanagerjava.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @PostMapping("/register")
    public Result registerUser(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");
        String email = request.get("email");
        String phoneNumber = request.get("phoneNumber");

        User user = new User();

        user.setUsername(username);
        user.setEmail(email);
        user.setPhoneNumber(phoneNumber);
        user.setPasswordHash(passwordEncoder.encode(password)); // 对密码进行加密
        user.setCreatedAt(new Date().toString());
        user.setLastLoginAt(new Date().toString());
        user.setStatus( 1); // 默认启用用户
        userService.insertUser(user); // 假设你有一个 insertUser 方法
        return Result.success("User registered successfully");
    }

    @PostMapping("/login")
    public Result loginUser(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");

        User user = userService.selectByUserName(username).get(0);
        if (user == null || !passwordEncoder.matches(password, user.getPasswordHash())) {
            return Result.error(401, "Invalid username or password");
        }

        String token = jwtTokenProvider.generateToken(username);

        // 登录成功，可以返回 token 或其他信息
        Map<String, String> response = new HashMap<>();
        response.put("token", token);
        response.put("username", username);
        return Result.success(response);
    }
}
